<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="送货单编号" prop="deliveryNoteNo">
        <el-input
          v-model="queryParams.deliveryNoteNo"
          placeholder="请输入送货单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入供货商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送货日期" prop="deliveryDate">
        <el-date-picker clearable
          v-model="queryParams.deliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择送货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:note:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-view"
          size="mini"
          :disabled="single"
          @click="handleDetail"
          v-hasPermi="['system:note:query']"
        >详情</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:note:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:note:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
      <el-table-column label="送货状态" align="center" prop="deliveryStatus" fixed="left" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deliveryStatus==='CREATED'" type="info">
            <i class="el-icon-info"></i> 已创建
          </el-tag>
          <el-tag v-else-if="scope.row.deliveryStatus==='CONFIRMED'" type="warning">
            <i class="el-icon-warning"></i> 已发货
          </el-tag>
          <el-tag v-else-if="scope.row.deliveryStatus==='RECEIVED'" type="success">
            <i class="el-icon-success"></i> 已收货
          </el-tag>
          <el-tag v-else type="info">
            {{ scope.row.deliveryStatus || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="送货单编号" align="center" prop="deliveryNoteNo" />
      <el-table-column label="采购订单编号" align="center" prop="orderNo" />
      <el-table-column label="供货商编码" align="center" prop="supplierCode" />
      <el-table-column label="供货商名称" align="center" prop="supplierName" />
      <el-table-column label="送货日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.deliveryStatus==='CREATED'"
            @click="confirmShipment(scope.row)"
          >确认发货</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            v-else
            @click="handlePrint(scope.row)"
          >打印</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:note:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:note:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改送货单对话框（重构） -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="采购订单">
              <el-button type="primary" size="mini" :disabled="detailMode" @click="openPOSelectDialog">选择采购订单</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="箱码">
              <el-button type="success" size="mini" :disabled="detailMode || !form.orderNo" @click="openBarcodeSelectDialog">选择箱码</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="供货商编码" prop="supplierCode">
              <el-input v-model="form.supplierCode" disabled placeholder="由采购订单回填" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供货商名称">
              <el-input v-model="form.supplierName" disabled placeholder="由采购订单回填" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="送货日期" prop="deliveryDate">
              <el-date-picker
                v-model="form.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd"
                disabled
                placeholder="当天日期自动填充">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单编号">
              <el-input v-model="form.orderNo" disabled placeholder="由采购订单回填" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">箱码列表</el-divider>
        <el-table :data="selectedBarcodes" size="mini" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column label="箱码" prop="barcode" width="160" />
          <el-table-column label="批次号" prop="batchNo" width="140" />
          <el-table-column label="存货编码" prop="inventoryCode" width="140" />
          <el-table-column label="存货名称" prop="inventoryName" />
          <el-table-column label="数量" prop="packQuantity" width="120" />
          <el-table-column label="单位" prop="unitName" width="120" />
        </el-table>

        <el-divider content-position="left">送货清单</el-divider>
        <el-table :data="bizDeliveryBatchList" size="mini" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column label="批次号" prop="batchNo" width="140" />
          <el-table-column label="存货编码" prop="inventoryCode" width="140" />
          <el-table-column label="存货名称" prop="inventoryName" />
          <el-table-column label="订单数量" prop="orderQuantity" width="120" />
          <el-table-column label="本次送货数量" prop="batchQuantity" width="140" />
          <el-table-column label="箱数" prop="batchBoxes" width="100" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!detailMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择采购订单弹窗 -->
    <el-dialog title="选择采购订单" :visible.sync="poSelectOpen" width="800px" append-to-body>
      <el-form :model="poQuery" inline size="small" label-width="100px">
        <el-form-item label="采购订单编号">
          <el-input v-model="poQuery.orderNo" placeholder="请输入采购订单编号" clearable @keyup.enter.native="poQuery.pageNum=1;loadPurchaseOrdersForSelection()" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="poQuery.pageNum=1;loadPurchaseOrdersForSelection()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="poQuery.orderNo='';poQuery.pageNum=1;loadPurchaseOrdersForSelection()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="poList" @row-click="handlePickPO" highlight-current-row>
        <el-table-column type="index" width="60" />
        <el-table-column label="订单编号" prop="orderNo" />
        <el-table-column label="供应商编码" prop="supplierCode" />
        <el-table-column label="订单状态" prop="orderStatus" />
        <el-table-column label="交货日期" prop="deliveryDate" />
      </el-table>
      <pagination
        v-show="poTotal>0"
        :total="poTotal"
        :page.sync="poQuery.pageNum"
        :limit.sync="poQuery.pageSize"
        @pagination="loadPurchaseOrdersForSelection"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPOSelection">确 认</el-button>
        <el-button @click="poSelectOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择箱码弹窗 -->
    <el-dialog title="选择箱码" :visible.sync="barcodeSelectOpen" width="900px" append-to-body>
      <el-form :model="barcodeQuery" inline size="small" label-width="80px">
        <el-form-item label="批次号">
          <el-input v-model="barcodeQuery.batchNo" placeholder="按批次号查询" clearable @keyup.enter.native="barcodeQuery.pageNum=1;loadBarcodesForSelection()" />
        </el-form-item>
        <el-form-item label="箱码">
          <el-input v-model="barcodeQuery.barcode" placeholder="按箱码查询" clearable @keyup.enter.native="barcodeQuery.pageNum=1;loadBarcodesForSelection()" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="barcodeQuery.pageNum=1;loadBarcodesForSelection()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="barcodeQuery.batchNo='';barcodeQuery.barcode='';barcodeQuery.pageNum=1;loadBarcodesForSelection()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="barcodeList" @selection-change="handlePickBarcodes" border>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="60" />
        <el-table-column label="箱码" prop="barcode" />
        <el-table-column label="批次号" prop="batchNo" />
        <el-table-column label="存货编码" prop="inventoryCode" />
        <el-table-column label="存货名称" prop="inventoryName" />
        <el-table-column label="数量" prop="packQuantity" />
      </el-table>
      <pagination
        v-show="barcodeTotal>0"
        :total="barcodeTotal"
        :page.sync="barcodeQuery.pageNum"
        :limit.sync="barcodeQuery.pageSize"
        @pagination="loadBarcodesForSelection"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmBarcodeSelection">确 认</el-button>
        <el-button @click="barcodeSelectOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印预览弹窗 -->
    <el-dialog title="打印预览" :visible.sync="printOpen" width="900px" append-to-body>
      <div ref="printArea" class="print-container">
        <div class="print-header">
          <div class="logo-box">
            <img src="/1.jpg" style="width:100%;height:100%;object-fit:contain" />
          </div>
          <div class="title">送货单</div>
          <div>
            <img :src="qrSrc" class="qr" />
          </div>
        </div>
        <div class="meta">
          <div class="left">
            <div class="field"><span class="label">供应商名称：</span><span class="value">{{ printHeader.supplierName }}</span></div>
            <div class="field"><span class="label">客户名称：</span><span class="value"></span></div>
          </div>
          <div class="right">
            <div class="field"><span class="label">送货日期：</span><span class="value">{{ parseTime(printHeader.deliveryDate, '{y}-{m}-{d}') }}</span></div>
            <div class="field"><span class="label">车牌号：</span><span class="value"></span></div>
          </div>
        </div>

        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>采购订单编码</th>
              <th>存货编码</th>
              <th>存货名称</th>
              <th>送货数量</th>
              <th>计量单位</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in printRows" :key="row.index">
              <td>{{ row.index }}</td>
              <td>{{ row.orderNo }}</td>
              <td>{{ row.inventoryCode }}</td>
              <td>{{ row.inventoryName }}</td>
              <td>{{ row.quantity }}</td>
              <td>{{ row.unitName }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="6">本单总数：{{ printTotalQuantity }}</td>
            </tr>
          </tfoot>
        </table>

        <div class="footer">
          <div class="field"><span class="label">送货人：</span><span class="value"></span></div>
          <div class="field"><span class="label">收货人：</span><span class="value"></span></div>
          <div class="field"><span class="label">检验员：</span><span class="value"></span></div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doPrint">打 印</el-button>
        <el-button @click="printOpen=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNote, getNote, delNote, addNote, updateNote } from "@/api/system/note"
import { listPurchase_order, listPurchaseOrderItems } from "@/api/system/purchase_order"
import { listBarcode, updateBarcode } from "@/api/system/barcode"

export default {
  name: "Note",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizDeliveryBatch: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 送货单表格数据
      noteList: [],
      // 送货单批次明细（聚合后的送货清单）
      bizDeliveryBatchList: [],
      // 已选择的箱码列表
      selectedBarcodes: [],
      // 采购订单弹窗
      poSelectOpen: false,
      poQuery: { orderStatus: 'DRAFT', orderNo: '', pageNum: 1, pageSize: 10 },
      poList: [],
      poTotal: 0,
      pickedPO: null,
      // 箱码弹窗
      barcodeSelectOpen: false,
      barcodeQuery: { orderNo: '', batchNo: '', barcode: '', pageNum: 1, pageSize: 10 },
      barcodeList: [],
      barcodeTotal: 0,
      pickedBarcodes: [],
      // 采购订单明细Map（itemId -> 明细）
      poItemsById: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情模式
      detailMode: false,
      // 打印预览
      printOpen: false,
      printHeader: { supplierName: '', deliveryDate: '', customerName: '', carPlate: '', deliveryNoteNo: '', orderNo: '' },
      printRows: [],
      printTotalQuantity: 0,
      qrSrc: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deliveryNoteNo: null,
        supplierCode: null,
        deliveryDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierCode: [
          { required: true, message: "供货商编码不能为空", trigger: "blur" }
        ],
        deliveryDate: [
          { required: true, message: "送货日期不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询送货单列表 */
    getList() {
      this.loading = true
      listNote(this.queryParams).then(response => {
        const rows = response.rows || []
        rows.sort((a, b) => Number(b.deliveryNoteId || 0) - Number(a.deliveryNoteId || 0))
        this.noteList = rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deliveryNoteId: null,
        deliveryNoteNo: null,
        supplierCode: null,
        supplierName: null,
        orderNo: null,
        deliveryDate: null,
        deliveryStatus: null,
        totalBoxes: null,
        totalQuantity: null,
        receiver: null,
        receivedTime: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      }
      this.bizDeliveryBatchList = []
      this.selectedBarcodes = []
      this.poItemsById = {}
      this.resetForm("form")
      this.detailMode = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deliveryNoteId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 送货日期默认当天且不可编辑
      this.form.deliveryDate = this.todayString()
      this.detailMode = false
      this.open = true
      this.title = "添加送货单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const deliveryNoteId = row.deliveryNoteId || this.ids
      getNote(deliveryNoteId).then(response => {
        this.form = response.data
        this.bizDeliveryBatchList = response.data.bizDeliveryBatchList
        this.open = true
        this.title = "修改送货单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将聚合后的送货清单作为明细提交
          this.form.bizDeliveryBatchList = this.bizDeliveryBatchList
          if (this.form.deliveryNoteId != null) {
            updateNote(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 附带选中的箱码到后端
            this.form.bizDeliveryBarcodeList = (this.selectedBarcodes || []).map(b => ({
              barcodeId: b.barcodeId,
              barcode: b.barcode,
              inventoryCode: b.inventoryCode,
              packQuantity: b.packQuantity,
              unitCode: b.unitCode
            }))
            addNote(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deliveryNoteIds = row.deliveryNoteId || this.ids
      this.$modal.confirm('是否确认删除送货单编号为"' + deliveryNoteIds + '"的数据项？').then(function() {
        return delNote(deliveryNoteIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 工具：当天 yyyy-MM-dd */
    todayString() {
      const d = new Date()
      const y = d.getFullYear()
      const m = String(d.getMonth()+1).padStart(2,'0')
      const day = String(d.getDate()).padStart(2,'0')
      return `${y}-${m}-${day}`
    },
    /** 打开选择采购订单 */
    openPOSelectDialog() {
      this.poQuery.orderStatus = 'DRAFT'
      this.poQuery.orderNo = ''
      this.poQuery.pageNum = 1
      this.poSelectOpen = true
      this.loadPurchaseOrdersForSelection()
    },
    /** 加载采购订单（仅DRAFT，可按订单号查询，含分页） */
    loadPurchaseOrdersForSelection() {
      const params = { orderStatus: this.poQuery.orderStatus }
      if (this.poQuery.orderNo) params.orderNo = this.poQuery.orderNo
      params.pageNum = this.poQuery.pageNum
      params.pageSize = this.poQuery.pageSize
      listPurchase_order(params).then(resp => {
        this.poList = resp.rows || []
        this.poTotal = Number(resp.total || 0)
      })
    },
    /** 选择某条采购订单（行点击） */
    handlePickPO(row) {
      this.pickedPO = row
    },
    /** 确认采购订单选择并回填 */
    confirmPOSelection() {
      if (!this.pickedPO) {
        this.$modal.msgError('请先选择采购订单')
        return
      }
      const row = this.pickedPO
      this.form.supplierCode = row.supplierCode
      this.form.orderNo = row.orderNo
      this.poSelectOpen = false
      // 加载订单明细以回填供应商名称并建立 item 索引
      listPurchaseOrderItems({ orderNo: row.orderNo }).then(resp => {
        const items = resp.rows || []
        this.form.supplierName = items.length ? items[0].supplierName : ''
        this.poItemsById = {}
        items.forEach(it => { this.poItemsById[it.itemId] = it })
      })
      // 清空已选箱码与送货清单（避免跨订单残留）
      this.selectedBarcodes = []
      this.bizDeliveryBatchList = []
    },
    /** 打开选择箱码弹窗（按订单号过滤） */
    openBarcodeSelectDialog() {
      if (!this.form.orderNo) {
        this.$modal.msgError('请先选择采购订单')
        return
      }
      this.barcodeSelectOpen = true
      this.barcodeQuery.orderNo = this.form.orderNo
      this.barcodeQuery.pageNum = 1
      this.loadBarcodesForSelection()
    },
    /** 加载箱码（按订单号 + 可按批次号/箱码查询，含分页） */
    loadBarcodesForSelection() {
      const params = { orderNo: this.barcodeQuery.orderNo }
      if (this.barcodeQuery.batchNo) params.batchNo = this.barcodeQuery.batchNo
      if (this.barcodeQuery.barcode) params.barcode = this.barcodeQuery.barcode
      params.pageNum = this.barcodeQuery.pageNum
      params.pageSize = this.barcodeQuery.pageSize
      params.barcodeStatus = 'GENERATED'
      listBarcode(params).then(resp => {
        this.barcodeList = resp.rows || []
        this.barcodeTotal = Number(resp.total || 0)
      })
    },
    /** 选择箱码（多选） */
    handlePickBarcodes(selection) {
      this.pickedBarcodes = selection
    },
    /** 确认选择箱码并生成送货清单 */
    confirmBarcodeSelection() {
      if (!this.pickedBarcodes || this.pickedBarcodes.length === 0) {
        this.$modal.msgError('请至少选择一个箱码')
        return
      }
      this.barcodeSelectOpen = false
      this.selectedBarcodes = this.pickedBarcodes
      this.computeDeliveryListFromSelectedBarcodes()
    },
    /** 从已选箱码按批次聚合生成送货清单 */
    computeDeliveryListFromSelectedBarcodes() {
      const groups = {}
      this.selectedBarcodes.forEach(b => {
        const key = b.batchNo
        if (!groups[key]) groups[key] = []
        groups[key].push(b)
      })
      const list = []
      Object.keys(groups).forEach(batchNo => {
        const rows = groups[batchNo]
        const boxes = rows.length
        // 数量字段为 packQuantity(BigDecimal)；转为Number后累加
        const deliveryQty = rows.reduce((sum, r) => sum + Number(r.packQuantity || 0), 0)
        const first = rows[0]
        const item = this.poItemsById[first.itemId] || {}
        list.push({
          // 明细入库字段
          itemId: first.itemId,
          orderNo: this.form.orderNo,
          batchNo: batchNo,
          inventoryCode: first.inventoryCode || item.inventoryCode,
          inventoryName: first.inventoryName || item.inventoryName,
          unitCode: first.unitCode || item.unitCode,
          // 显示与提交用
          orderQuantity: item.orderQuantity || item.quantity || 0,
          batchQuantity: deliveryQty,
          batchBoxes: boxes
        })
      })
      this.bizDeliveryBatchList = list
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset()
      const deliveryNoteId = row.deliveryNoteId || this.ids
      getNote(deliveryNoteId).then(async response => {
        const data = response.data || {}
        this.form = data
        const batches = data.bizDeliveryBatchList || []
        const barcodes = data.bizDeliveryBarcodeList || []
        this.bizDeliveryBatchList = batches
        // 构建批次索引（deliveryBatchId -> 批次）
        const batchById = {}
        batches.forEach(b => { if (b.deliveryBatchId) batchById[b.deliveryBatchId] = b })
        // 加载订单明细以补全名称与单位
        let itemsById = {}
        if (data.orderNo) {
          try {
            const resp = await listPurchaseOrderItems({ orderNo: data.orderNo })
            const items = resp.rows || []
            items.forEach(it => { itemsById[it.itemId] = it })
            // 为送货清单补全 inventoryName、unitName、orderQuantity
            this.bizDeliveryBatchList = batches.map(b => {
              const it = itemsById[b.itemId] || {}
              return Object.assign({}, b, {
                inventoryName: b.inventoryName || it.inventoryName || '',
                unitName: b.unitName || it.unitName || '',
                orderQuantity: b.orderQuantity || it.orderQuantity || it.quantity || 0
              })
            })
          } catch (e) {
            // ignore
          }
        }
        // 补全箱码的批次号、存货名称、单位
        this.selectedBarcodes = (barcodes || []).map(b => {
          const batch = batchById[b.deliveryBatchId] || {}
          const it = batch.itemId ? (itemsById[batch.itemId] || {}) : {}
          return Object.assign({}, b, {
            batchNo: b.batchNo || batch.batchNo || '',
            inventoryCode: b.inventoryCode || batch.inventoryCode || '',
            inventoryName: b.inventoryName || it.inventoryName || '',
            unitCode: b.unitCode || batch.unitCode || '',
            unitName: b.unitName || it.unitName || ''
          })
        })
        this.detailMode = true
        this.open = true
        this.title = "送货单详情"
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deliveryNoteIds = row.deliveryNoteId || this.ids
      this.$modal.confirm('是否确认删除送货单编号为"' + deliveryNoteIds + '"的数据项？').then(function() {
        return delNote(deliveryNoteIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 工具：当天 yyyy-MM-dd */
    todayString() {
      const d = new Date()
      const y = d.getFullYear()
      const m = String(d.getMonth()+1).padStart(2,'0')
      const day = String(d.getDate()).padStart(2,'0')
      return `${y}-${m}-${day}`
    },
    /** 打开选择采购订单 */
    openPOSelectDialog() {
      this.poQuery.orderStatus = 'DRAFT'
      this.poQuery.orderNo = ''
      this.poQuery.pageNum = 1
      this.poSelectOpen = true
      this.loadPurchaseOrdersForSelection()
    },
    /** 加载采购订单（仅DRAFT，可按订单号查询，含分页） */
    loadPurchaseOrdersForSelection() {
      const params = { orderStatus: this.poQuery.orderStatus }
      if (this.poQuery.orderNo) params.orderNo = this.poQuery.orderNo
      params.pageNum = this.poQuery.pageNum
      params.pageSize = this.poQuery.pageSize
      listPurchase_order(params).then(resp => {
        this.poList = resp.rows || []
        this.poTotal = Number(resp.total || 0)
      })
    },
    /** 选择某条采购订单（行点击） */
    handlePickPO(row) {
      this.pickedPO = row
    },
    /** 确认采购订单选择并回填 */
    confirmPOSelection() {
      if (!this.pickedPO) {
        this.$modal.msgError('请先选择采购订单')
        return
      }
      const row = this.pickedPO
      this.form.supplierCode = row.supplierCode
      this.form.orderNo = row.orderNo
      this.poSelectOpen = false
      // 加载订单明细以回填供应商名称并建立 item 索引
      listPurchaseOrderItems({ orderNo: row.orderNo }).then(resp => {
        const items = resp.rows || []
        this.form.supplierName = items.length ? items[0].supplierName : ''
        this.poItemsById = {}
        items.forEach(it => { this.poItemsById[it.itemId] = it })
      })
      // 清空已选箱码与送货清单（避免跨订单残留）
      this.selectedBarcodes = []
      this.bizDeliveryBatchList = []
    },
    /** 打开选择箱码弹窗（按订单号过滤） */
    openBarcodeSelectDialog() {
      if (!this.form.orderNo) {
        this.$modal.msgError('请先选择采购订单')
        return
      }
      this.barcodeSelectOpen = true
      this.barcodeQuery.orderNo = this.form.orderNo
      this.barcodeQuery.pageNum = 1
      this.loadBarcodesForSelection()
    },
    /** 加载箱码（按订单号 + 可按批次号/箱码查询，含分页） */
    loadBarcodesForSelection() {
      const params = { orderNo: this.barcodeQuery.orderNo }
      if (this.barcodeQuery.batchNo) params.batchNo = this.barcodeQuery.batchNo
      if (this.barcodeQuery.barcode) params.barcode = this.barcodeQuery.barcode
      params.pageNum = this.barcodeQuery.pageNum
      params.pageSize = this.barcodeQuery.pageSize
      params.barcodeStatus = 'GENERATED'
      listBarcode(params).then(resp => {
        this.barcodeList = resp.rows || []
        this.barcodeTotal = Number(resp.total || 0)
      })
    },
    /** 选择箱码（多选） */
    handlePickBarcodes(selection) {
      this.pickedBarcodes = selection
    },
    /** 确认选择箱码并生成送货清单 */
    confirmBarcodeSelection() {
      if (!this.pickedBarcodes || this.pickedBarcodes.length === 0) {
        this.$modal.msgError('请至少选择一个箱码')
        return
      }
      this.barcodeSelectOpen = false
      this.selectedBarcodes = this.pickedBarcodes
      this.computeDeliveryListFromSelectedBarcodes()
    },
    /** 从已选箱码按批次聚合生成送货清单 */
    computeDeliveryListFromSelectedBarcodes() {
      const groups = {}
      this.selectedBarcodes.forEach(b => {
        const key = b.batchNo
        if (!groups[key]) groups[key] = []
        groups[key].push(b)
      })
      const list = []
      Object.keys(groups).forEach(batchNo => {
        const rows = groups[batchNo]
        const boxes = rows.length
        // 数量字段为 packQuantity(BigDecimal)；转为Number后累加
        const deliveryQty = rows.reduce((sum, r) => sum + Number(r.packQuantity || 0), 0)
        const first = rows[0]
        const item = this.poItemsById[first.itemId] || {}
        list.push({
          // 明细入库字段
          itemId: first.itemId,
          orderNo: this.form.orderNo,
          batchNo: batchNo,
          inventoryCode: first.inventoryCode || item.inventoryCode,
          inventoryName: first.inventoryName || item.inventoryName,
          unitCode: first.unitCode || item.unitCode,
          // 显示与提交用
          orderQuantity: item.orderQuantity || item.quantity || 0,
          batchQuantity: deliveryQty,
          batchBoxes: boxes
        })
      })
      this.bizDeliveryBatchList = list
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/note/export', {
        ...this.queryParams
      }, `note_${new Date().getTime()}.xlsx`)
    },
    /** 确认发货：置状态为 CONFIRMED，并把所有关联箱码的送货编码写入当前送货单编号 */
    async confirmShipment(row) {
      const id = row.deliveryNoteId
      try {
        const resp = await getNote(id)
        const data = resp.data || {}
        // 1) 更新送货单状态
        data.deliveryStatus = 'CONFIRMED'
        await updateNote(data)
        // 2) 批量写入箱码的送货编码（deliveryNoteNo）
        const noteNo = data.deliveryNoteNo || row.deliveryNoteNo
        const barcodes = data.bizDeliveryBarcodeList || []
        if (noteNo && barcodes.length) {
          await Promise.all(barcodes.map(b => updateBarcode({ barcodeId: b.barcodeId, deliveryNoteNo: noteNo })))
        }
        this.$modal.msgSuccess('已确认发货，并写入箱码送货编码')
        this.getList()
      } catch (e) {
        // 保持原弹窗行为，静默失败
      }
    },
    /** 打印（加载详情、填充模板并打开预览） */
    async handlePrint(row) {
      const id = row.deliveryNoteId
      this.$modal.loading('正在生成打印预览...')
      try {
        const resp = await getNote(id)
        const d = resp.data || {}
        this.printHeader = {
          supplierName: d.supplierName || '',
          deliveryDate: d.deliveryDate || '',
          customerName: '',
          carPlate: '',
          deliveryNoteNo: d.deliveryNoteNo || '',
          orderNo: d.orderNo || ''
        }
        // 送货清单行
        let rows = d.bizDeliveryBatchList || []
        // 若缺失单位或名称，尝试按订单号补齐
        if (this.printHeader.orderNo) {
          try {
            const itemsResp = await listPurchaseOrderItems({ orderNo: this.printHeader.orderNo })
            const itemsById = {}
            ;(itemsResp.rows || []).forEach(it => { itemsById[it.itemId] = it })
            rows = rows.map(b => {
              const it = itemsById[b.itemId] || {}
              return Object.assign({}, b, {
                inventoryName: b.inventoryName || it.inventoryName || '',
                unitName: b.unitName || it.unitName || ''
              })
            })
          } catch (e) { /* ignore */ }
        }
        this.printRows = rows.map((b, idx) => ({
          index: idx + 1,
          orderNo: this.printHeader.orderNo,
          inventoryCode: b.inventoryCode,
          inventoryName: b.inventoryName,
          quantity: Number(b.batchQuantity || 0),
          unitName: b.unitName || ''
        }))
        this.printTotalQuantity = this.printRows.reduce((s, r) => s + Number(r.quantity || 0), 0)
        const dataText = this.printHeader.deliveryNoteNo ? `DELIVERY_NOTE:${this.printHeader.deliveryNoteNo}` : (d.deliveryNoteId ? `DELIVERY_NOTE_ID:${d.deliveryNoteId}` : 'DELIVERY_NOTE')
        this.qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(dataText)}`
        this.printOpen = true
      } finally {
        this.$modal.closeLoading()
      }
    },
    /** 执行系统打印（仅打印预览区域） */
    doPrint() {
      const area = this.$refs.printArea
      if (!area) { window.print(); return }
      const css = this.printCss()
      const html = area.outerHTML
      const w = window.open('', '_blank')
      w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>送货单</title><style>${css}</style></head><body>${html}</body></html>`)
      w.document.close(); w.focus()
      setTimeout(() => { w.print(); w.close() }, 100)
    },
    /** 打印样式（用于新窗口打印） */
    printCss() {
      return `
      .print-container{ width:820px; margin:0 auto; font-family:"Microsoft YaHei",Arial,sans-serif; color:#000; }
      .print-header{ display:flex; justify-content:space-between; align-items:flex-start; }
      .logo-box{ width:260px; height:90px; border:1px solid #999; }
      .title{ text-align:center; font-size:22px; font-weight:bold; margin:8px 0 12px; }
      .meta{ display:flex; justify-content:space-between; margin:8px 0; }
      .meta .left,.meta .right{ width:48%; }
      .field{ margin:6px 0; }
      .field .label{ display:inline-block; width:100px; }
      .field .value{ display:inline-block; min-width:240px; border-bottom:1px dashed #999; }
      .qr{ width:120px; height:120px; }
      table{ width:100%; border-collapse:collapse; margin-top:8px; }
      th,td{ border:1px solid #999; padding:6px 8px; font-size:13px; text-align:center; }
      tfoot td{ text-align:right; font-weight:bold; }
      .footer{ display:flex; justify-content:space-between; margin-top:18px; }
      .footer .field .label{ width:auto; }
      .footer .field .value{ min-width:180px; }
      `
    }
  }
}
</script>
<style scoped>
.print-container{ width:820px; margin:0 auto; font-family:"Microsoft YaHei",Arial,sans-serif; color:#000; }
.print-header{ display:flex; justify-content:space-between; align-items:flex-start; }
.logo-box{ width:260px; height:90px; border:1px solid #999; }
.title{ text-align:center; font-size:22px; font-weight:bold; margin:8px 0 12px; }
.meta{ display:flex; justify-content:space-between; margin:8px 0; }
.meta .left,.meta .right{ width:48%; }
.field{ margin:6px 0; }
.field .label{ display:inline-block; width:100px; }
.field .value{ display:inline-block; min-width:240px; border-bottom:1px dashed #999; }
.qr{ width:120px; height:120px; }
 table{ width:100%; border-collapse:collapse; margin-top:8px; }
 th,td{ border:1px solid #999; padding:6px 8px; font-size:13px; text-align:center; }
 tfoot td{ text-align:right; font-weight:bold; }
 .footer{ display:flex; justify-content:space-between; margin-top:18px; }
 .footer .field .label{ width:auto; }
 .footer .field .value{ min-width:180px; }
</style>
